#include "DbClient.h"

void DbClient::init()
{
    //create the database object
    mySqlDatabase = QSqlDatabase::addDatabase("QMYSQL");
    //set database credentials
    mySqlDatabase.setHostName("localhost");
    mySqlDatabase.setDatabaseName("Ocmf");
    mySqlDatabase.setUserName("root");
    mySqlDatabase.setPassword("ocmf");
}

DbClient::DbClient()
{
    init();
}

QQueue<Experiment*> * DbClient::GetScheduledExperiments(qlonglong serverId)
{
    //instanciate experiment queue
    QQueue<Experiment*> * experimentQueue = new QQueue<Experiment*>();

    //try to open a connection to the database
    if(!mySqlDatabase.open())return experimentQueue;

    QSqlQuery sqlQuery(SqlStatments::SELECT_SCHEDULED_EXPERIMENTS, mySqlDatabase);
    sqlQuery.bindValue(":chamberId", serverId);

    //execute the sql statement
    if(sqlQuery.exec())
        while(sqlQuery.next())
        {
            //create new experiment object
            Experiment * experiment = new Experiment(sqlQuery.value(0).toByteArray());

            //add the experiment to the queue
            experimentQueue->enqueue(experiment);
        }

    //close the connection to the database
    mySqlDatabase.close();

    //return
    return experimentQueue;
}

void DbClient::SetServerStatus(qlonglong chamberId, OcmfServerStatus ocmfServerStatus, Experiment * experiment)
{
    //try to open a connection to the database
    if(!mySqlDatabase.open())return;

    //create sql query
    QSqlQuery sqlQuery(SqlStatments::UPDATE_SERVER_STATUS, mySqlDatabase);
    sqlQuery.bindValue(":lastStatus", ocmfServerStatus);
    sqlQuery.bindValue(":lastUpdated", QDateTime::currentDateTime().toString());
    if(experiment == NULL)
        sqlQuery.bindValue(":runningExperiment", experiment->FileName);
    else
        sqlQuery.bindValue(":runningExperiment", "NONE");
    sqlQuery.bindValue(":chamberId", chamberId);

    //execute sql query
    sqlQuery.exec();

    //close the connection to the database
    mySqlDatabase.close();
}



